package com.youthfilmic.yuejian.util;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.youthfilmic.yuejian.conn.QiniuConn;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by youweixi on 15/10/26.
 */
public class QiniuAPI {
    /**
     * 生成凭证，这个是一个加密值，应该不会变的
     * */
    private static Auth auth = Auth.create(QiniuConn.ACCESS_KEY, QiniuConn.SECRET_KEY);
    /**
     * 重用UploadManager
     * */
    private static UploadManager uploadManager = new UploadManager();
    /**
     * 重用BuckManager
     * */
    private static BucketManager bucketManager = new BucketManager(auth);

    // 简单上传，使用默认策略
    public static String getUpToken(){
        return auth.uploadToken(QiniuConn.BUCKET);
    }

    // 覆盖上传
    public static String getUpToken(String key){
        return auth.uploadToken(QiniuConn.BUCKET, key);
    }

    // 设置指定上传策略
    public static String getUpTokenWithParam(){
        return auth.uploadToken(QiniuConn.BUCKET, null, 3600, new StringMap()
                .put("callbackUrl", "call back url").putNotEmpty("callbackHost", "")
                .put("callbackBody", "key=$(key)&hash=$(etag)"));
    }

    // 设置预处理、去除非限定的策略字段
    public static String getUpToken3(){
        return auth.uploadToken(QiniuConn.BUCKET, null, 3600, new StringMap()
                .putNotEmpty("persistentOps", "").putNotEmpty("persistentNotifyUrl", "")
                .putNotEmpty("persistentPipeline", ""), true);
    }

    /**
     * 生成上传token
     *
     * @param bucket  空间名
     * @param key     key，可为 null
     * @param expires 有效时长，单位秒。默认3600s
     * @param policy  上传策略的其它参数，如 new StringMap().put("endUser", "uid").putNotEmpty("returnBody", "")。
     *        scope通过 bucket、key间接设置，deadline 通过 expires 间接设置
     * @param strict  是否去除非限定的策略字段，默认true
     * @return 生成的上传token
     */
    public static String uploadToken(String bucket, String key, long expires, StringMap policy, boolean strict){
        return null;
    }


    //要求url可公网正常访问，不指定 key 时以文件的 hash 值为 key
    public static void fetch(String url , String bucket){
        try {
            bucketManager.fetch(url, bucket);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    public static String fetch(String url , String bucket , String key){
        //要求url可公网正常访问
        try {
            bucketManager.fetch(url, bucket, key);
        } catch (QiniuException e) {
            e.printStackTrace();
            return url;
        }
        return QiniuConn.FILE_SERVER_DOMAIN + "/" + key;
    }

    /**
     * 生成文件KEY的函数
     * 【WARNING】添加文件路径类型之后我们需要在这里进行配置
     * */
    public static String getFileKey(int fileType , int pathType ){
        StringBuffer buffer = new StringBuffer();
        if (pathType == QiniuConn.FILE_PATH_TYPE_TEMP) buffer.append(QiniuConn.FILE_PATH_NAME_TEMP);
        else if (pathType == QiniuConn.FILE_PATH_TYPE_WEIXIN_PIC) buffer.append(QiniuConn.FILE_PATH_NAME_WEIXIN_PIC);
        else if (pathType == QiniuConn.FILE_PATH_TYPE_WEIXIN_IMG) buffer.append(QiniuConn.FILE_PATH_NAME_WEIXIN_IMG);

        buffer.append(getRamdomName());

        if (fileType == QiniuConn.FILE_TYPE_IMG_JPG) buffer.append(".jpg");

        return buffer.toString();
    }

    /**
     * 获取随机文件名
     * */
    private static String getRamdomName(){
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + String.format("%03d", new Random().nextInt(999));
    }

    public static void main(String[] args){
        //System.out.println(getUpToken0());
        fetch("http://img30.360buyimg.com/da/jfs/t2137/300/838732673/95480/b08a3e43/562dca10Ned523e25.jpg", QiniuConn.BUCKET);
    }

}
